package com.cyp.blogsystem.service.impl;

import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;

import com.cyp.blogsystem.exception.BusinessException;
import com.cyp.blogsystem.service.OssService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.util.Date;

@Service
@RequiredArgsConstructor
@Slf4j
public class OssServiceImpl implements OssService {

  @Value("${aliyun.oss.endpoint}")
  private String endpoint;

  @Value("${aliyun.oss.accessKeyId}")
  private String accessKeyId;

  @Value("${aliyun.oss.accessKeySecret}")
  private String accessKeySecret;

  @Value("${aliyun.oss.bucketName}")
  private String bucketName;

  @Override
  public String uploadFile(MultipartFile file, String type) {
    // 1. 初始化OSS客户端
    OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);
    try {
      // 2. 生成文件路径
      String fileName = generateFileName(file.getOriginalFilename(), type);

      // 3. 上传文件
      ossClient.putObject(bucketName, fileName, file.getInputStream());

      // 4. 生成文件访问URL
      return generateFileUrl(fileName);

    } catch (Exception e) {
      log.error("文件上传失败", e);
      throw new BusinessException("文件上传失败");
    } finally {
      // 5. 关闭OSS客户端
      ossClient.shutdown();
    }
  }

  /**
   * 生成文件名
   */
  private String generateFileName(String originalFilename, String type) {
//    String ext = FilenameUtils.getExtension(originalFilename);
//    return String.format("%s/%s/%s.%s",
//        type,
//        DateUtil.format(new Date(), "yyyyMM"),
//        IdUtil.fastSimpleUUID(),
//        ext);
    return null;
  }

  /**
   * 生成文件URL
   */
  private String generateFileUrl(String fileName) {
    return String.format("https://%s.%s/%s", bucketName, endpoint, fileName);
  }
}